
#include "main.hpp"


using namespace idf::pn532;
using namespace std;

#define NFC_TAG         "nfc_task"

extern void show_uuid(uint8_t *pUid);

extern "C" void nfc_task(void *pvParameter)
{
    static PN532_HardwareSerial Serial1;
    static PN532_HSU pn532hsu(Serial1);
    static PN532 nfc(pn532hsu);
    uint32_t versiondata;

    while(1)
    {
        nfc.begin();
        versiondata = nfc.getFirmwareVersion();
        if (versiondata) 
        {
            break;
        }
        //ESP_LOGI(NFC_TAG, "Didn't find PN53x board");
        vTaskDelay(pdMS_TO_TICKS(3000));
    }
    
    // Got ok data, print it out!
    ESP_LOGI(NFC_TAG, "Found chip PN5 %X"   ,(uint8_t)((versiondata>>24)&0xFF));
    ESP_LOGI(NFC_TAG, "Firmware ver. %d%d"  ,(uint8_t)((versiondata>>16)&0xFF),(uint8_t)((versiondata>>8)&0xFF));

    
    // Set the max number of retry attempts to read from a card
    // This prevents us from waiting forever for a card, which is
    // the default behaviour of the PN532.
    nfc.setPassiveActivationRetries(0xFF);
    
    // configure board to read RFID tags
    nfc.SAMConfig();
      
    ESP_LOGI(NFC_TAG, "Waiting for an ISO14443A card");


    while (1)
    {
      bool success;
      uint8_t uid[20] = { 0, 0, 0, 0, 0, 0, 0 };  // Buffer to store the returned UID
      int16_t uidLength;                        // Length of the UID (4 or 7 bytes depending on ISO14443A card type)
      
      // Wait for an ISO14443A type cards (Mifare, etc.).  When one is found
      // 'uid' will be populated with the UID, and uidLength will indicate
      // if the uid is 4 bytes (Mifare Classic) or 7 bytes (Mifare Ultralight)
      success = nfc.inListPassiveTarget(&uid[0], &uidLength);
      
      if (success) 
      {
        ESP_LOGI(NFC_TAG, "Found a card!");
        ESP_LOGI(NFC_TAG, "UID Length: %d bytes",uidLength);
        ESP_LOGI(NFC_TAG, "UID Value: ");
        ESP_LOG_BUFFER_HEXDUMP(NFC_TAG, uid, uidLength, ESP_LOG_INFO);

        //show_uuid(&uid[0]);
        
        //for (uint8_t i=0; i < uidLength; i++) 
        //{
        //ESP_LOGI(NFC_TAG, " 0x%X",uid[i]);
        //}
        // Wait 1 second before continuing
        vTaskDelay(pdMS_TO_TICKS(1000));
      }
      else
      {
        // PN532 probably timed out waiting for a card
        //ESP_LOGI(NFC_TAG, "Timed out waiting for a card");
        vTaskDelay(pdMS_TO_TICKS(1000));
      }
    }
}


